#pragma once

#include <sys/epoll.h>
#include <iostream>
#include "log.hpp"
class Epoll
{
    const static int gnum;
    const static int timeout;

public:
    Epoll(int gtimeout = timeout)
        : _timeout(gtimeout)
    {
    }
    ~Epoll()
    {
    }

    void CreateEpoll()
    {
        _epfd = epoll_create(gnum);
        if (_epfd < 0)
        {
            logMessage(ERROR, "%s", "CreateEpoll failed");
            exit(5);
        }
    }

    bool CtlEpoll(int sock, uint32_t events)
    {
        events |= EPOLLET;
        struct epoll_event ev;
        ev.events = events;
        ev.data.fd = sock;
        int n = epoll_ctl(_epfd, EPOLL_CTL_MOD, sock, &ev);
        return n == 0;
    }

    bool AddSockToEpoll(int sock, uint32_t events)
    {
        struct epoll_event ev;
        ev.events = events;
        ev.data.fd = sock;
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, sock, &ev);
        return n == 0;
    }

    bool DelFromEpoll(int sock)
    {
        int n = epoll_ctl(_epfd, EPOLL_CTL_DEL, sock, nullptr);
        return n == 0;
    }
    int WaitEpoll(struct epoll_event *revs, int num)
    {
        return epoll_wait(_epfd, revs, num, _timeout);
    }

private:
    int _epfd;
    int _timeout;
};
const int Epoll::gnum = 128;
const int Epoll::timeout = 500;